<?PHP	
include('config/config.php');
require('php/functions.php');
	//Connect to database
	$conn = mysql_connect($cfg["connection"]["host"], $cfg["connection"]["userName"], $cfg["connection"]["password"]) 
		or die ('Error Cannot Connect to MySQL');
	@mysql_select_db($cfg["connection"]["database"]) or die( "Unable to select database");
	
	$query = "SELECT curdate() AS date";
	$result = mysql_query($query);
	$curdate = mysql_fetch_array($result);
	$curdate = $curdate['date'];
	
	$tbl_name = $cfg['tbl']['shopLocation'];
	$query = "SELECT shopId FROM $tbl_name";
	$result = mysql_query($query);
	$shopIDs = array();
	while ($shopID = mysql_fetch_assoc($result, MYSQL_NUM)) $shopIDs[] = $shopID[0];
	$noShop = mysql_num_rows($result);
	
	foreach ($shopIDs as $shopID) {
		$filename = "/usr/local/apache/htdocs/admin-panel/uploads/Transaction_"."$shopID"."_"."$curdate.txt";
		
		$file = fopen( $filename, "r" );
		if (!$file) {
			println("FILE ERROR $filename");
			continue;
		}
		$tbl_name=$cfg['tbl']['inventory'];	

		$filesize = filesize( $filename );
		$filetext = fread( $file, $filesize );

		fclose( $file );

		$content = explode("\n", $filetext);
		foreach ($content as $line)
		{
			list($barcode, $unitSold, $date) = explode(":",$line);			
			$query = "UPDATE $tbl_name SET local_stock=local_stock-$unitSold WHERE itemId = \"$barcode\";";
			$result = mysql_query($query);
			$query = "INSERT INTO local_transaction VALUES ($barcode, '".$date."', $shopID, $unitSold)";
			//println($query);
			$result = mysql_query($query);
		}	
	}
	header("Location: ./stockTrend.php");
?>
